import store from '../store/index.js'

// 格式化日期
/*
* @formate 'yyyy-MM-dd HH:mm:ss'
*
*/
export function formateDate(time, formate) {
  const date = new Date(time)
  const arr1 = formate.split(' ')
  let fomatArray1 = []
  let fomatArray2 = []
  if (arr1[0]) {
    fomatArray1 = arr1[0].split('-')
  }
  if (arr1[1]) {
    fomatArray2 = arr1[1].split(':')
  }
  const data = {
    yyyy: date.getFullYear(),
    MM: date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1),
    dd: date.getDate() > 9 ? date.getDate() : '0' + date.getDate(),
    HH: date.getHours() > 9 ? date.getHours() : '0' + date.getHours(),
    mm: date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes(),
    ss: date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds()
  }
  let dateStr = ''
  for (const i in fomatArray1) {
    if (i < fomatArray1.length - 1) {
      dateStr = dateStr + data[fomatArray1[i]] + '-'
    } else {
      dateStr = dateStr + data[fomatArray1[i]]
    }
  }
  for (const i in fomatArray2) {
    if (i < fomatArray2.length - 1) {
      if (i === '0') {
        dateStr = dateStr + ' '
      }
      dateStr = dateStr + data[fomatArray2[i]] + ':'
    } else {
      dateStr = dateStr + data[fomatArray2[i]]
    }
  }
  return dateStr
}
// 返回当前日期所在第几周
export function getWeekNum(date) {
  const currentDate = new Date(date)
  const fisrtDate = new Date(currentDate.getFullYear(), 0, 1)
  const d = Math.round((currentDate.valueOf() - fisrtDate.valueOf()) / 86400000)
  const weekNum = Math.ceil((d + ((fisrtDate.getDay() + 1) - 1)) / 7)
  return weekNum
}
// 返回周几
export function getWeekDay(date) {
  const currentDate = new Date(date)
  const weekArray = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
  return weekArray[currentDate.getDay()]
}
// 比较日期
export function compareDate(date1, date2) {
  const time1 = new Date(date1).getTime()
  const time2 = new Date(date2).getTime()
  return time1 - time2
}
// 计算提前或推后日期
export function computeDays(currentDate, days, type) {
  const curentTime = new Date(currentDate).getTime()
  const daysTime = days * 3600 * 24 * 1000
  let resutTime = 0
  if (type === 1) {
    resutTime = curentTime + daysTime
  } else {
    resutTime = curentTime - daysTime
  }
  return formateDate(resutTime, 'Y-m-d h:mm:s')
}
// token 管理
export function setNewToken(tokenData, timeLen) {
  const startTime = new Date().getTime()
  const tokenInfo = {
    data: tokenData,
    endTime: startTime + timeLen
  }
  localStorage.tokenInfo = JSON.stringify(tokenInfo)
}
export function getTokenInfo() {
  // let endTime = new Date().getTime()
  if (localStorage.tokenInfo) {
    return JSON.parse(localStorage.tokenInfo).data
  } else {
    return false
  }
}
// token 管理
export function setNewIdenity(timeLogin) {
  const startTime = new Date().getTime()
  localStorage.lastTime = Number(timeLogin) + startTime
}

/**
 * 树形数据转换
 * @param {*} data
 * @param {*} id
 * @param {*} pid
 */
export function treeDataTranslate(data, id = 'id', pid = 'parentId') {
  var res = []
  var temp = {}
  for (var i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i]
  }
  for (var k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = []
      }
      if (!temp[data[k][pid]]['_level']) {
        temp[data[k][pid]]['_level'] = 1
      }
      data[k]['_level'] = temp[data[k][pid]]._level + 1
      temp[data[k][pid]]['children'].push(data[k])
    } else {
      res.push(data[k])
    }
  }
  return res
}

/**
 * 是否有权限
 * @param {*} key
 */
export function isAuth(key) {
  return JSON.parse(localStorage.getItem('permissions') || '[]').indexOf(key) !== -1 || false
}

/**
 * 设置permissions
 * @param {*}
 */
export function setPermissions(permissions) {
  // store.commit('setPermissions', permissions)
  localStorage.setItem('permissions', JSON.stringify(permissions))
}

/**
 * 获取permissions
 * @param {*}
 */
export function hasPerm(key) {
  if (localStorage.permissions?.length) {
    return JSON.parse(localStorage.permissions).indexOf(key) !== -1 || false
  }
}

// Dialog Drawer 通用底部按钮添加loading事件
/*
* @footerBtnListName '[String] drawerController'
* @triggerName '[String]confirm'
* @event '[Boolean] true false'
*/
export function btnLoading(footerBtnListName, triggerName, event) {
  this[footerBtnListName].forEach(item => {
    if (item.trigger === triggerName) {
      this.$set(item, 'loading', event)
    }
  })
}

// 手机号码校验规则
export function checkTelephone(rule, value, callback) {
  if (value === '') {
    callback(new Error('请输入联系方式'))
  } else if (value.length !== 11) {
    callback(new Error('联系方式长度有误'))
  } else {
    const reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
    if (!reg.test(value)) {
      callback(new Error('请输入正确的联系方式'))
    } else {
      callback()
    }
  }
}

// 身份证号码校验规则
export function checkIdCardNumber(rule, value, callback) {
  if (value === '') {
    callback(new Error('请输入身份证号'))
  } else if (value.length !== 15 && value.length !== 18) {
    callback(new Error('身份证号长度有误'))
  } else {
    const reg18 = /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    const reg15 = /^[1-9]\d{5}\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{2}[0-9Xx]$/
    if (reg18.test(value) || reg15.test(value)) {
      callback()
    } else {
      callback(new Error('请输入正确的身份证号'))
    }
  }
}

// 字符长度校验规则
// test: [
//   { required: true, message: '请输入测试', trigger: 'blur' },
//   { length: 7, message: '测试长度不正确', validator: validateLength, trigger: 'blur' }
// ]
export function validateLength(rule, value, callback, length) {
  if (value.length !== rule.length) {
    callback(new Error(rule.message))
  } else {
    callback()
  }
}

// 根据文件结构获取路由列表
// @params ignoreList 要忽略匹配的字符串构成的数组
export function getRouteChildren(ignoreList = ['children']) {
  let files = require.context('../pages', true, /.vue$/).keys()
  ignoreList.forEach(string => {
    files = files.filter(item => {
      if (item.indexOf(string) === -1) {
        return item
      }
    })
  })
  let path = JSON.parse(JSON.stringify(files))
  path = path.map(item => {
    item = item.replace(/^./, '')
    return item
  })
  files = files.map(item => {
    let pathList = item.split('/')
    pathList = pathList.map(path => {
      return path.replace(/[A-Z]+/g, (word) => {
        if (path.indexOf(word) === 0) {
          return word.toLowerCase()
        } else {
          return `-${word.toLowerCase()}`
        }
      })
    })
    item = pathList.join('/')
    item = item.replace(/\/index.vue$/, '')
    item = item.replace(/.vue$/, '')
    item = item.replace(/^./, '')
    return item
  })
  const children = files.map((item, index) => {
    return {
      path: item,
      component: (resolve) => require([`@/pages${path[index]}`], resolve)
    }
  })
  return children
}

// 打印
export function doPrint(val) {
  const ordonnance = document.getElementById(val).contentWindow
  setTimeout(() => {
    ordonnance.print()
  }, 100)
}
